﻿Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_QuanLyHoSoChamDut_ThongBao
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim itm As New ListItem("--- Chọn ---", "  ")
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request("Certifiedid") Is Nothing AndAlso Request("Certifiedid") <> 0 Then
                hidID.Value = Request("Certifiedid")
                Load2Grid()
            End If
        End If
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities

            Dim _curHuyenId As Integer = Session("HuyenId")
            'load List PrositionDict
            Dim _j = (From q In _data.PositionDicts Order By q.Sort Select q).ToList
            With ddlCertifiedSignerPosition
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            With ddlCertifiedSignFor
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            'load list StaffDict
            Dim _SN = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedSignerName
                .DataSource = _SN
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            Dim _BH = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedBeHaft
                .DataSource = _BH
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With


            'load giấy đề nghị nếu có rồi
            'Dim intUserId As Integer = IIf(IsNothing(Session("UserID")), 0, Session("UserID"))
            'Dim use = (From q In _data.Users Where q.UserId = intUserId Select q.UserName).FirstOrDefault

            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

            CapNhatMCC.Visible = False
            If Not p Is Nothing Then
                'show link Update MCC
                If Not p.SoBienNhan Is Nothing Then
                    Using abc As New AutoDevModel.AutoDevEntities
                        Dim kkkk = (From q In abc.HoSoes Where q.SoBienNhan = p.SoBienNhan And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not kkkk Is Nothing Then
                            CapNhatMCC.Visible = True
                            hplLinkMcc.NavigateUrl = "../../Page/TiepNhan/UpdateMcc.aspx?s=" & kkkk.SoBienNhan.ToString
                            hplLinkMcc.Text = "đây"
                        End If
                    End Using
                End If


                'hidID.Value = p.CertifiedID
                'p.CertifiedStatus = 0 '0, chua duoc duyet
                If Not p.CertifiedCode Is Nothing AndAlso p.CertifiedCode <> "" Then
                    txtCertifiedCode.Text = p.CertifiedCode
                    If Not p.CertifiedDate Is Nothing Then
                        txtCertifiedDate.Text = CType(p.CertifiedDate, Date).ToString("dd/MM/yyyy")
                    Else

                        txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
                    End If

                    'txtCertifiedCode.Enabled = False
                Else
                    txtCertifiedCode.Text = btnGenGCN()
                End If
                'thong tin ca nhan


                'load CertifiedProvinderOrg by DeptCertifieds
                Dim _l = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList

                With ddlCertifiedProviderOrg
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                'load CertifiedDeptName by DeptCertifieds
                With ddlCertifiedDeptName
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                Dim _DoViCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "001" Order By q.Sort Select q.Name).FirstOrDefault
                Dim _PhongBanCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "002" Order By q.Sort Select q.Name).FirstOrDefault
                'Đơn vị cấp
                If Not p.CertifiedProviderOrg Is Nothing Then
                    ddlCertifiedProviderOrg.SelectedValue = p.CertifiedProviderOrg
                Else
                    ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                End If
                'Phòng ban cấp
                If Not p.CertifiedDeptName Is Nothing Then
                    ddlCertifiedDeptName.SelectedValue = p.CertifiedDeptName
                Else
                    ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                End If

                'chức vụ người được ký thay
                If Not p.CertifiedSignFor Is Nothing Then
                    ddlCertifiedSignFor.SelectedValue = p.CertifiedSignFor
                Else
                    ddlCertifiedSignFor.SelectedValue = ""
                End If
                'Tên Người được ký thay
                If Not p.CertifiedBeHaft Is Nothing Then
                    ddlCertifiedBeHaft.SelectedValue = p.CertifiedBeHaft
                Else
                    ddlCertifiedBeHaft.SelectedValue = ""
                End If
                'Người ký
                If Not p.CertifiedSignerName Is Nothing Then
                    ddlCertifiedSignerName.SelectedValue = p.CertifiedSignerName
                Else
                    ddlCertifiedSignerName.SelectedValue = ""
                End If
                'Chức vụ người ký
                If Not p.CertifiedSignerPosition Is Nothing Then
                    ddlCertifiedSignerPosition.SelectedValue = p.CertifiedSignerPosition
                Else
                    ddlCertifiedSignerPosition.SelectedValue = ""
                End If


            End If
        End Using
    End Sub
    Protected Function btnGenGCN() As String
        Dim strCode As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Using _data As New VSEntities
            Dim curCode As String = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            curCode = curCode & "800"
            Dim max As String = (From q In _data.CertifiedHouseholds Where q.ProvinceId = _curHuyenId And q.CertifiedCode.Contains(curCode) And q.CertifiedDate > "2014/01/01" Order By q.CertifiedCode Descending Select q.CertifiedCode).FirstOrDefault
            '52I80002416
            Dim HuyenCode = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            Try
                Dim _new As Integer = CType(max.Replace(HuyenCode, ""), Integer) + 1
                If _new > 0 Then
                    strCode = HuyenCode & _new.ToString.PadLeft(5)
                Else
                    strCode = HuyenCode & "800" & _new.ToString.PadLeft(5)
                End If
            Catch ex As Exception
                strCode = HuyenCode & "800" & "00001"
            End Try
            hidCertifiedCode.Value = strCode ' lưu vao hidden field để lưu
            txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
            Return strCode

        End Using
    End Function
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub

    Protected Sub btnExportWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportWord.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        Dim strFileName As String = strDocFile.Split("\")(strDocFile.Split("\").Length - 1)
        Excute_Javascript("SetDownFile('" & MainDomain & "GCNKD/" & strFileName & "');", Me.Page)


    End Sub
    Protected Sub btnExportPdf_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportPdf.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            Dim strFileName As String = strPdfFile.Split("\")(strPdfFile.Split("\").Length - 1)

            Response.Redirect(MainDomain & "GCNKD/" & strFileName)
        End If



    End Sub

    Function getDocFile() As String
        Dim strResult As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\HouseholdCertificate.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim cls As New clsDAPrint
                Dim dt As DataTable = cls.CertifiedHouseholdSelectById(hidID.Value, _curHuyenId)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    doc.MailMerge.Execute(dt)
                    'insert nganh nghe
                    Dim builder As DocumentBuilder = New DocumentBuilder(doc)

                    Dim strNganhNghe As String = ""
                    Dim strNganhNgheChiTiet As String = ""

                    Using _data As New VSEntities
                        Dim p = (From q In _data.CertifiedHouseholdNganhNghes Where q.CertifiedID = hidID.Value Select q).ToList
                        For Each a In p
                            Dim nganhnghe = (From k In _data.DanhMucNganhNghes Where k.Id = a.DanhMucNganhNgheID Select k).FirstOrDefault
                            strNganhNghe = strNganhNghe & nganhnghe.Name & " (" & nganhnghe.Code & ")" & ", "
                            strNganhNgheChiTiet = strNganhNgheChiTiet & a.Description & ", "
                            'If Not a.Description Is Nothing AndAlso a.Description <> "" Then
                            '    strNganhNghe = strNganhNghe & a.Description & " (" & nganhnghe.Code & ")" & ", "
                            'Else
                            '    strNganhNghe = strNganhNghe & nganhnghe.Name & " (" & nganhnghe.Code & ")" & ", "
                            'End If
                        Next


                        'cap lan dau CertifiedDateFirst

                        Dim lstOfCertified As List(Of CertifiedHousehold)
                        Dim curCertified = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

                        If Not curCertified Is Nothing AndAlso curCertified.ParentId <> 0 Then
                            lstOfCertified = (From q In _data.CertifiedHouseholds
                                 Where (q.ParentId = curCertified.ParentId Or q.CertifiedID = curCertified.ParentId) Order By q.CertifiedDate Select q).ToList
                        Else
                            lstOfCertified = (From q In _data.CertifiedHouseholds
                                 Where q.CertifiedID = hidID.Value Or q.ParentId = hidID.Value Order By q.CertifiedDate Select q).ToList
                        End If

                        ' Dim lstOfCertified = (From q In _data.CertifiedHouseholds Where q.CertifiedCode = txtCertifiedCode.Text And (q.ParentId = hidID.Value Or q.CertifiedID = hidID.Value) Order By q.CertifiedUp_Time Ascending Select q).ToList
                        Dim i = 0
                        For Each a In lstOfCertified
                            Dim _date As Date = CType(a.CertifiedDate, Date)
                            If i = 0 Then
                                builder.MoveToMergeField("CertifiedDateFirst")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim lblDate As String = ""
                                    builder.Write(_date.Day & " tháng " & _date.Month & " năm " & _date.Year)
                                Else
                                    builder.Write("")
                                End If

                            End If
                            If i = 1 And (i = lstOfCertified.Count - 1) Then
                                builder.MoveToMergeField("CertifiedSecond")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký thay đổi lần thứ: 1 ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            End If

                            'ko phai lan dau va cap hon 2 lan
                            If (i = lstOfCertified.Count - 1) AndAlso (lstOfCertified.Count > 2) Then
                                builder.MoveToMergeField("CertifiedFinal")
                                If Not a.CertifiedDate Is Nothing Then
                                    Dim str = "Đăng ký thay đổi lần thứ:  " & i.ToString & " ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year
                                    builder.Write(str)
                                End If
                            End If
                            i = i + 1
                        Next

                        'cap lan dau CertifiedDateSecond if null
                        builder.MoveToMergeField("CertifiedSecond")
                        builder.Write("")
                        'cap lan dau CertifiedDateLast if null
                        builder.MoveToMergeField("CertifiedFinal")
                        builder.Write("")
                        ' ky thay
                        Dim kt = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault
                        If Not kt Is Nothing Then
                            ' vốn kinh doanh
                            If Not kt.Biz_InvestCapital Is Nothing Then
                                builder.MoveToMergeField("Biz_InvestCapital_Name")
                                builder.Write(FormatCurrency(kt.Biz_InvestCapital).Replace(",", ".")) 'vốn kinh doanh

                            End If

                            If Not kt.CertifiedSignFor Is Nothing AndAlso kt.CertifiedSignFor.Trim <> "" Then
                                builder.MoveToMergeField("CertifiedSignerFor")
                                builder.Write("KT. " & kt.CertifiedSignFor.ToUpper)
                            Else
                                builder.MoveToMergeField("CertifiedSignerFor")
                                builder.Write("")
                            End If
                            'ngay sinh
                            If kt.Ow_BirthDate.Length >= 8 And kt.Ow_BirthDate.IndexOf("/") < 0 Then
                                builder.MoveToMergeField("Ow_BirthDate_Name")
                                Dim strDate As String = kt.Ow_BirthDate.Substring(0, 2) & "/" & kt.Ow_BirthDate.Substring(2, 2) & "/" & kt.Ow_BirthDate.Substring(4, 4)
                                builder.Write(strDate)
                            Else
                                builder.MoveToMergeField("Ow_BirthDate_Name")
                                builder.Write(kt.Ow_BirthDate)
                            End If

                            'ngay cap cmnd
                            If Not kt.Ow_CardDate Is Nothing Then
                                builder.MoveToMergeField("Ow_CardDate_Name")
                                builder.Write(CType(kt.Ow_CardDate, Date).ToString("dd/MM/yyyy"))
                            Else
                                builder.MoveToMergeField("Ow_CardDate_Name")
                                Write("")
                            End If

                            ' gioi tinh
                            If kt.Ow_Sex = 1 Then
                                builder.MoveToMergeField("Ow_Sex_Name")
                                builder.Write("Nam")
                            Else
                                builder.MoveToMergeField("Ow_Sex_Name")
                                builder.Write("Nữ")
                            End If
                            ' loại giấy tờ
                            If kt.Ow_Doc_ID = "" Or kt.Ow_Doc_ID = "0" Then
                                builder.MoveToMergeField("Ow_Doc_ID_Name")
                                builder.Write("Giấy chứng minh nhân dân")
                            Else
                                Dim strLoaiGiay = (From q In _data.CertifiedPaperDicts Where q.Id = kt.Ow_Doc_ID Select q).FirstOrDefault
                                If Not strLoaiGiay Is Nothing Then
                                    builder.MoveToMergeField("Ow_Doc_ID_Name")
                                    builder.Write(strLoaiGiay.Name)
                                End If
                            End If


                        End If

                        'noted
                        Dim _huyen = (From q In _data.Configs Where q.ProvinceId = _curHuyenId Select q).FirstOrDefault
                        If Not _huyen Is Nothing AndAlso Not _huyen.Ref2 Is Nothing Then
                            builder.MoveToMergeField("Noted")
                            builder.Write(_huyen.Ref2)
                        Else
                            builder.MoveToMergeField("Noted")
                            builder.Write("")
                        End If
                        'gop von kinh doanh
                        Dim lstGopVon = (From q In _data.CertifiedHouseholdMembers Where q.CertifiedID = hidID.Value Select q).ToList
                        If Not lstGopVon Is Nothing AndAlso lstGopVon.Count > 0 Then

                            'header gop von
                            builder.MoveToMergeField("TitleSection6")
                            builder.InsertHtml("<b style='font-size:19px' ><font face='Times New Roman'> 6. Danh sách cá nhân góp vốn thành lập hộ kinh doanh</font></b> <i>(nếu có)</i>")

                            Dim strHMLBeginTable As String = "<table border='1' cellspacing='0' cellpadding='0' style='width:100%;border-collapse:collapse;'>"
                            strHMLBeginTable = strHMLBeginTable & "<tr><td style='valign=top'>STT</td><td width='110'  style='valign=top'>Tên thành viên</td><td  style='valign=top'>Nơi đăng ký hộ khẩu thường trú</td><td>Giá trị phần vốn góp (VNĐ)" & _
                                "</td><td>Tỷ lệ (%)</td><td width='120'  style='valign=top'>Số giấy chứng minh nhân dân (hoặc chứng thực cá nhân hợp pháp khác)</td><td  style='valign=top'>Ghi chú</td></tr>"

                            Dim strHTMLEndTable As String = "</table>"
                            Dim strHTML As String = ""
                            'danh sach gop von
                            Dim _Stt As Integer = 1
                            For Each a In lstGopVon
                                strHTML = strHTML & "<tr>"
                                strHTML = strHTML & "<td>" & _Stt.ToString & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberName & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberAddress & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberValues & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberRate & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberCard & "</td>"
                                strHTML = strHTML & "<td>" & a.MemberDes & "</td>"
                                strHTML = strHTML & "</tr>"
                                _Stt = _Stt + 1
                            Next
                            builder.MoveToMergeField("Section6")
                            builder.InsertHtml(strHMLBeginTable & strHTML & strHTMLEndTable)
                        Else
                            builder.MoveToMergeField("TitleSection6")
                            builder.InsertHtml("")
                            builder.MoveToMergeField("Section6")
                            builder.Write("")
                        End If

                    End Using
                    builder.MoveToMergeField("Biz_Career")
                    builder.Write(strNganhNghe.Trim.TrimEnd(","))

                    builder.MoveToMergeField("Biz_Career_Chitiet")
                    builder.Write(strNganhNgheChiTiet.Trim.TrimEnd(","))

                    strResult = applicationPath & "GCNKD"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    'set filename = soCN

                    strResult &= txtCertifiedCode.Text & "-" & Format(Now, "yyyyMMddfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        doc = Nothing
                    End If


                End If

            End If

        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/QuanLyHoSo/List.aspx';", Me.Page, True)
        End Try

        Return strResult
    End Function

    Protected Sub UpdateThongtin()
        ' If hidCertifiedCode.Value <> "" Then
        Using _data As New VSEntities
            Dim p = (From k In _data.CertifiedHouseholds Where k.CertifiedID = hidID.Value Select k).FirstOrDefault
            If Not p Is Nothing Then
                p.CertifiedDate = StringToDate(txtCertifiedDate.Text)

                If p.ParentId = 0 Then
                    p.CertifiedUp_Time = 1
                Else 'cung parent id
                    p.CertifiedUp_Time = (From q In _data.CertifiedHouseholds Where q.ParentId = p.ParentId Select q).Count + 1
                End If


                p.CertifiedCode = txtCertifiedCode.Text
                'Đơn vị cấp
                p.CertifiedProviderOrg = ddlCertifiedProviderOrg.SelectedValue
                'Phòng ban cấp
                p.CertifiedDeptName = ddlCertifiedDeptName.SelectedValue
                'Thay mặt Người ký
                p.CertifiedSignFor = ddlCertifiedSignFor.SelectedValue
                'Tên Người ký thay
                p.CertifiedBeHaft = ddlCertifiedBeHaft.SelectedValue
                'Người ký
                p.CertifiedSignerName = ddlCertifiedSignerName.SelectedValue
                'Chức vụ người ký
                p.CertifiedSignerPosition = ddlCertifiedSignerPosition.SelectedValue
                _data.SaveChanges()
            End If
        End Using
        'End If
    End Sub
End Class

